package com.youxin.cpcenter.service.impl;

import com.youxin.busfoundation.bean.ResponseObject;
import com.youxin.busfoundation.bean.login.UserInfo;
import com.youxin.busfoundation.common.LoginAuth;
import com.youxin.busfoundation.enums.FollowLeadsStatus;
import com.youxin.cpcenter.bean.*;
import com.youxin.cpcenter.service.CluePoolCompanyService;
import com.youxin.cpcenter.service.EntMemberService;
import com.youxin.cpcenter.service.SalesFunnelService;
import com.youxin.foundation.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName: SalesFunnelServiceImpl
 * @Description: 销售漏斗业务
 * @author Kris.wang
 * @date 2017-12-09
 */
@Service("salesFunnelService")
public class SalesFunnelServiceImpl implements SalesFunnelService {

    @Autowired
    private CluePoolCompanyService cluePoolCompanyService;

    @Autowired
    private EntMemberService entMemberService;

    /**
     * @desc 销售漏斗统计
     * @param requestBean
     * @return
     * @throws Exception
     */
    @Override
    public ResponseObject totalSalesFunnel(RequestSalesfunnelBean requestBean) throws Exception {
        try {
            UserInfo userInfo= LoginAuth.getUserInfo(); //会员信息

            /*
             *  计算统计
             *  漏斗算法：
             *    线索总数（1层）：公司线索池所有线索总数，状态=all
             *    跟进中（2层）：状态!=未认领
             *    有意向（3层）：状态= 有意向 + 已成交
             *    已成交（4层）：状态=已成交
             *  根据企业UID获取对应数据,分两种情况：
             *  一、管理员展示所有的企业成员线索
             *  二、非管理员展示自身的线索
             */
            Float clueTotal=0.0f;
            Float clueFollowup=0.0f;
            Float clueUnFollowup=0.0f;
            Float clueIntention=0.0f;
            Float clueDone = 0.0f;
            RequestPoolCompanyTotalBean bean = new RequestPoolCompanyTotalBean();
            bean.setCompanyUid(userInfo.getCompanyUid());
            bean.setStartTime(BigInteger.valueOf(requestBean.getStartTime()));
            bean.setEndTime(BigInteger.valueOf(requestBean.getEndTime()));

            //管理员&&非管理员
            if (!userInfo.isAdmin()) {
                bean.setMemberId(BigInteger.valueOf(userInfo.getEntMemberId()));
            } else { //管理员
                bean.setMemberId(BigInteger.valueOf(requestBean.getMemberId()));
            }

            List<CluePoolCompanyTotalBean> cluePoolCompanyTotalList= cluePoolCompanyService.total(bean);
            for (CluePoolCompanyTotalBean item:cluePoolCompanyTotalList) {
                /*FollowLeadsStatus leadsStatus=FollowLeadsStatus.valueOf(item.getStatus());
                switch (leadsStatus) {
                    case UnFollow:
                        entity.setUnfollow(item.getTotal());
                        break;
                    case Flollowing:
                        entity.setFollow(item.getTotal());
                        break;
                    case HaveIntention:
                        entity.setHaveIntention(item.getTotal());
                        break;
                    case DealDone:
                        entity.setDealDone(item.getTotal());
                        break;
                    default:
                        break;
                }*/
                if (item.getStatus() == 2) { //已跟进
                    clueFollowup = item.getTotal();
                } else if (item.getStatus() == 3) { //有意向
                    clueIntention = item.getTotal();
                } else if (item.getStatus() == 4) { //已成交
                    clueDone = item.getTotal();
                } else { //未跟进
                    clueUnFollowup = item.getTotal();
                }
            }
            clueTotal = clueUnFollowup+clueFollowup + clueIntention + clueDone; //总数
            Float clueFollowupTotal = clueFollowup+clueDone+clueIntention;//跟进中
            Float clueIntentionTotal = clueTotal-clueFollowup-clueUnFollowup;//有意向
            Float clueDoneTotal = clueDone;//已成交

            Float fClueTofollowupRate=0.0f;
            Float fClueFollowupRate=0.0f;
            Float fClueIntentionRate=0.0f;
            Float fClueDoneRate=0.0f;
            fClueTofollowupRate = clueTotal > 0 ? (clueUnFollowup)/clueTotal*100:0.0f;
            fClueFollowupRate = clueTotal > 0 ? (clueFollowup)/clueTotal*100:0.0f;
            fClueIntentionRate = clueTotal > 0 ? (clueIntention)/clueTotal*100:0.0f;
            fClueDoneRate = clueTotal > 0 ? (clueDone)/clueTotal*100:0.0f;

            Float percentConversionOne = 0.0f;
            Float percentConversionTwo = 0.0f;
            Float percentConversionThree = 0.0f;
            percentConversionOne = clueTotal > 0 ? (clueFollowupTotal)/clueTotal*100:0.0f;
            percentConversionTwo = clueFollowup > 0 ?(clueIntentionTotal)/clueTotal*100:0.0f;
            percentConversionThree = clueIntention > 0 ? clueDoneTotal/clueTotal*100:0.0f;

            // 返回记录
            SalesfunnelBean salesfunnelBean = new SalesfunnelBean();
            salesfunnelBean.setClueTotal(clueTotal);
            salesfunnelBean.setClueFollowup(clueFollowupTotal);
            salesfunnelBean.setClueIntention(clueIntentionTotal);
            salesfunnelBean.setClueDone(clueDoneTotal);
            salesfunnelBean.setClueDoneRate(String.format("%.2f", fClueDoneRate)+"%");
            salesfunnelBean.setClueIntentionRate(String.format("%.2f", fClueIntentionRate)+"%");
            salesfunnelBean.setClueFollowupRate(String.format("%.2f", fClueFollowupRate)+"%");
            salesfunnelBean.setClueTofollowupRate(String.format("%.2f", fClueTofollowupRate)+"%");
            salesfunnelBean.setPercentConversionOne(String.format("%.2f", percentConversionOne)+"%");
            salesfunnelBean.setPercentConversionTwo(String.format("%.2f", percentConversionTwo)+"%");
            salesfunnelBean.setPercentConversionThree(String.format("%.2f", percentConversionThree)+"%");
            return ResponseObject.successObject(salesfunnelBean);
        } catch (Exception e) {
            return ResponseObject.successObject();
        }
    }

    /**
     * @desc 销售漏斗-跟进人列表
     * @return
     * @throws Exception
     */
    @Override
    public ResponseObject followupList() throws Exception {
        try {
            UserInfo userInfo= LoginAuth.getUserInfo(); //会员信息

            // 返回结果
            List<Map<String,String>> list = new ArrayList();

            // 初始化全部
            Map<String,String> map = new HashMap<String,String>();
            map.put("member_id","0");
            map.put("member_name","全部");
            list.add(map);

            // 判断是否企业管理员
            if (userInfo.isAdmin()) {
                RequestEntMemberBean requestEntMemberBean = new RequestEntMemberBean();
                requestEntMemberBean.setCompanyUid(userInfo.getCompanyUid());
                List<EntMemberBean> entMemberBeanList = entMemberService.selectMembersByCompanyUid(requestEntMemberBean);
                for (EntMemberBean item:entMemberBeanList) {
                    Map<String,String> tmpMap = new HashMap<String,String>();
                    tmpMap.put("member_id",item.getId().toString());
                    tmpMap.put("member_name",item.getRealName());
                    list.add(tmpMap);
                }
            // 非管理员
            } else {
                Long memberUid = userInfo.getEntMemberId();
                Map<String,String> tmpMap = new HashMap<String,String>();
                tmpMap.put("member_id",memberUid.toString());
                tmpMap.put("member_name",userInfo.getRealname());
                list.add(tmpMap);
            }
            return ResponseObject.successObject(list);
        } catch (Exception e) {
            return ResponseObject.successObject();
        }
    }

}
